package com.jsyl.web.config.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 系统异常捕获
 * 
 * @author binbinccut@163.com
 *
 */
public class SYSErrorFilter extends OncePerRequestFilter {

	private static final Logger LOG = LoggerFactory.getLogger(SYSErrorFilter.class);

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String cxt = request.getContextPath();
		Integer statusCode = null;
		try {
			filterChain.doFilter(request, response);
		} catch (UnauthorizedException e) {
			LOG.error("UnauthorizedException:", e);
			statusCode = 403;
		} catch (UnauthenticatedException e) {
			LOG.error("UnauthenticatedException:", e);
			statusCode = 403;
		} catch (Exception e) {
			LOG.error("System Exception:", e);
			statusCode = 500;
		}
		if (statusCode != null) {
			response.setStatus(statusCode);
			response.sendRedirect(cxt + "/" + statusCode);
		}
	}
}
